import socket
import network
import camera
import time


def do_connect():
    # 连接wifi
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('meik30s', '5201314ygyu')
        
        while not wlan.isconnected():
            pass
    print('网络配置:', wlan.ifconfig())

do_connect()

def wireless_video_transfer():
    
    # 摄像头初始化
    try:
       camera.init(0, format=camera.JPEG)
    except Exception as e:
        camera.deinit()
        camera.init(0, format=camera.JPEG)

    # 其他设置：
    # 上翻下翻
    camera.flip(0)
    #左/右
    camera.mirror(1)

    # 分辨率
    camera.framesize(camera.FRAME_HVGA)

    # 特效
    camera.speffect(camera.EFFECT_NONE)
    # 白平衡
    camera.whitebalance(camera.WB_HOME)
    

    # 饱和
    camera.saturation(0)
  
    # 亮度
    camera.brightness(0)

    # 对比度
    camera.contrast(0)
    
    # 质量
    camera.quality(10)
    
    
    # socket UDP 的创建
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)
    try:
        while True:
            buf = camera.capture()  # 获取图像数据
            s.sendto(buf, ("192.168.89.56", 7788))  # 向服务器发送图像数据,注意连接手机热点，会导致ESP32与电脑IP一直变化
            time.sleep(0.1)


    except:
        pass
    finally:
        camera.deinit()
     
    
    
    
if __name__=="__main__":
    wireless_video_transfer()
   
    
    
